package com.yzg.design;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author misterWei
 * @create 2020年05月16号:00点07分
 * @mailbox forcontinue@163.com
 * <p>
 * 使用lock 的条件变量 使用三个线程 执行5次  abcabcabcabcabc
 */
@Slf4j(topic = "c.waitNotifyCrossOut")
public class LockCrossOut {
    public static void main(String[] args) throws InterruptedException {
        LoopPrint loopPrint = new LoopPrint();
        Condition conditiona = loopPrint.newCondition();
        Condition conditionb = loopPrint.newCondition();
        Condition conditionc = loopPrint.newCondition();
        new Thread(()->{
            loopPrint.printf("a",conditiona,conditionb);
        },"t1").start();
        new Thread(()->{
            loopPrint.printf("b",conditionb,conditionc);
        },"t2").start();
        new Thread(()->{
            loopPrint.printf("c",conditionc,conditiona);
        },"t3").start();
        TimeUnit.SECONDS.sleep(2L);
        loopPrint.lock();
        try {
          conditiona.signal();
      }finally {
            loopPrint.unlock();
      }
    }

    /**
     * a 0 1
     * b 1 2
     * c 2 3
     * .
     */
    static class LoopPrint extends ReentrantLock{
       int loopNumber = 5;
        public void printf(String content,Condition current,Condition next){
            for (int i = 0; i < loopNumber; i++) {
                lock();
                try {
                    current.await();
                    System.out.print(content);
                    next.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    unlock();
                }
            }
        }

    }

}
